package com.yykj.template.server.service.impl;

import com.yykj.common.util.LocalUploadFile;
import com.yykj.common.vo.ResultVO;
import com.yykj.prescription.client.dto.PrescriptionDetailDTO;
import com.yykj.prescription.client.enums.PrescriptionType;
import com.yykj.prescription.client.feign.PrescriptionFeignClient;
import com.yykj.template.server.client.dto.ConsultationReportDTO;
import com.yykj.template.server.service.TemplateService;
import com.yykj.template.server.util.FreemarkerTools;
import com.yykj.template.server.util.ImageTool;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.fit.cssbox.demo.ImageRenderer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
@Slf4j
public class TemplateServiceImpl implements TemplateService {
    @Override
    public String generateConsultationReport(ConsultationReportDTO dto) throws IOException, TemplateException {
        ModelMap modelMap = new ModelMap();
        modelMap.put("report", dto);
        String templateName = "ConsultationReport.ftl";
        String html = FreemarkerTools.ftlToString(modelMap, templateName);
        String dir = getTempDir();
        String htmlFilePath = dir + "ConsultationReport.html";
        String imageFilePath = dir + "ConsultationReport.png";
        String imgPath = FreemarkerTools.turnImage(html, htmlFilePath, imageFilePath, 600, 800);
        System.out.println("文件生成路径" + imgPath);
        return imgPath;
    }

    @Override
    public String generatePrescriptionNote(String prescriptionId) throws Exception {
        ImageRenderer render = new ImageRenderer();
        String fileName = prescriptionId + ".png";
        File outPath = new File("./temp/");
        if(!outPath.exists()){
            outPath.mkdirs();
        }
        String outFileName = "./temp/" + fileName;
        FileOutputStream out = new FileOutputStream(outFileName);
        String url = domain + "/ftl/prescription/template/" + prescriptionId;

        render.renderURL(url, out, ImageRenderer.Type.PNG);
        out.close();
        return LocalUploadFile.uploadFile(new File(outFileName),fileName);
    }

    private String getTempDir() {
        String dir = "./temp/";
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        return dir;
    }

    @Value("${project.domain}")
    private String domain;

}
